package com.shop.interceptor;

import com.shop.common.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Object handler) throws Exception {
        // 将请求和响应转换为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取session对象（不创建新的session）
        HttpSession session = request.getSession(false);

        // 检查session中是否存在用户信息
        if (session != null && session.getAttribute(Constants.Session.USER) != null) {
            // 用户已登录，放行请求
            return true;
        } else {
            // 用户未登录，重定向到登录页面
            // 拿到model，设置提示信息

            if (session != null) {
                session.setAttribute(Constants.Session.MESSAGE, "请先登录");
            }
            response.sendRedirect(request.getContextPath() + "/user/login");
        }
        return false;
    }
}
